#include "CDevilLoader.h"

#include <IL/il.h>
#include <IL/ilu.h>
#include "../system.h"

//----------------------------------------------
void CDevilLoader::init()
{
	ilInit();
	iluInit();
}

//----------------------------------------------
bool CDevilLoader::load(CImage& oImage, const xstring& sPath)
{
	ILuint uiIlId;
	ilGenImages(1, &uiIlId);
	ilBindImage(uiIlId);

	bool bIsOk = true;
	if ( ilLoadImage(sPath.c_str()) == IL_FALSE )
	{
		ILenum error = ilGetError();
		const char* sError = (const char*)iluErrorString(error);
		std::string str = sError;
		str += " : \n";
		log(str.c_str());
		bIsOk = false;
	}

	if (bIsOk)
	{
		ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);
		int iWidth		= ilGetInteger(IL_IMAGE_WIDTH);
		int iHeight		= ilGetInteger(IL_IMAGE_HEIGHT);
		if (iWidth > 0 && iHeight > 0)
		{
			oImage.createBuffer(iWidth, iHeight);
			ILuint uiBytesCopied = ilCopyPixels(0, 0, 0, iWidth, iHeight, 1, IL_RGB, IL_UNSIGNED_BYTE, oImage.getBuffer());
			if (uiBytesCopied == 0)
			{
				oImage.releaseBuffer();
				bIsOk = false;
			}
		}
		else
		{
			bIsOk = false;
		}
	}

	if ( ilGetError() != IL_NO_ERROR )
	{
		// Flush error stack
		while ( ilGetError() != IL_NO_ERROR );

		bIsOk = false;
	}

	ilDeleteImage(uiIlId);

	return bIsOk;
}
